package org.yoki.edu.portal.web.rest.portal.auth;

import com.yunzhitx.cloud.common.model.InvokeResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yoki.edu.common.protocol.portal.exception.PortalException;
import org.yoki.edu.common.protocol.portal.exception.enums.PortalErrorStatusEnum;
import org.yoki.edu.common.protocol.portal.v1.sender.PortalV1PapMsgSender;
import org.yoki.edu.common.utils.encrypt.EncryptUtils;
import org.yoki.edu.portal.core.portal.vo.WeiXinPassReqVo;
import org.yoki.edu.portal.core.radius.domain.Radcheck;
import org.yoki.edu.portal.web.rest.portal.PortalWeChatTempLogoutThread;
import org.yoki.edu.portal.web.utils.CommonUtils;
import tk.mybatis.mapper.util.StringUtil;

import java.util.Map;
import java.util.UUID;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2017/12/7$ 15:41$
 */
@Controller
@RequestMapping("portal/auth/weChat")
public class PortalWeChatAuthRest {

    @Value("${portal.base.url}")
    private String baseUrl;

    @Value("${portal.ac.ip}")
    private String acIp;
    @Value("${portal.ac.port}")
    private Integer acPort;

    @Value("${weixin.mp.appId}")
    private String appId;
    @Value("${weixin.mp.shopId}")
    private String shopId;
    @Value("${weixin.mp.secretKey}")
    private String secretKey;
    @Value("${weixin.mp.wxRedirectUrl}")
    private String wxRedirectUrl;

    /**
     * 微信认证
     *
     * @return
     */
    @RequestMapping("toWxAuth")
    public String toWxAuth(WeiXinPassReqVo vo, Model model) {
        if (null == vo || CommonUtils.isEmpty(vo.getUserpriip(), vo.getSsid())) {
            model.addAttribute("error", "参数错误，请返回重试！");
        } else {
            String loginIp = vo.getUserpriip();

            //创建临时账号
            int serialNo = (int) (65535 * Math.random());
            String userName = UUID.randomUUID().toString();
            String password = UUID.randomUUID().toString();
            Radcheck radcheck = new Radcheck();
            radcheck.setUsername(userName);
            radcheck.setValue(password);
            radcheck.setLoginType("weChat");
            radcheck.setLoginIp(loginIp);
            radcheck.setDeviceMac(vo.getDeviceMac());
            try {
                radcheck.saveOrUpdatePwd();
                PortalV1PapMsgSender sender = new PortalV1PapMsgSender();
                sender.sendAndParseReqAuth(serialNo, loginIp, userName, password, acIp, acPort);
                sender.sendAffAckAuth(serialNo, loginIp, acIp, acPort);
            } catch (PortalException e) {
                if (e.getType() != PortalErrorStatusEnum.authLinkHadCreate.getType()) {
                    e.printStackTrace();
                    return "error";
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
            PortalWeChatTempLogoutThread thread = new PortalWeChatTempLogoutThread(userName, acIp, acPort);
            thread.start();
            String extend = userName;
            String authUrl = baseUrl + "portal/auth/weChat/weChatCallBack";
            vo.setAppId(appId);
            vo.setTimestamp(System.currentTimeMillis() + "");
            model.addAttribute("appId", appId);
            model.addAttribute("shopId", shopId);
            model.addAttribute("authUrl", authUrl);
            model.addAttribute("mac", vo.getDeviceMac());
//            model.addAttribute("ssidmac", vo.getSsidmac());
//            model.addAttribute("ssid", vo.getSsid());
            model.addAttribute("ssid", vo.getSsid());
            String sign = EncryptUtils.encryptMD5(appId + extend + vo.getTimestamp() + shopId + authUrl + vo.getDeviceMac() + vo.getSsid() + secretKey);
            model.addAttribute("sign", sign);
            model.addAttribute("extend", extend);
            model.addAttribute("timestamp", vo.getTimestamp());
        }
        return "wxAuth";
    }

    /**
     * 获取微信认证地址
     *
     * @return
     */
    @RequestMapping(value = "weChatCallBack")
    public ResponseEntity<InvokeResult<Map<String, String>>> weChatCallBack(String extend, String openId, String tid) {
        InvokeResult invokeResult = null;
        if (StringUtil.isEmpty(openId)) {
            return new ResponseEntity<>(invokeResult, HttpStatus.BAD_REQUEST);
        }
        String userName = extend;
        //跟新信息
        Radcheck radcheck = Radcheck.selectWeChatTypeByUserName(userName);
        if (null != radcheck) {
            System.out.println("微信wifi上网，[userName：" + userName + "] [openId :" + openId + "]");
            radcheck.setOpenId(openId);
            try {
                radcheck.update();
            } catch (Exception e) {
                e.printStackTrace();
                return new ResponseEntity<>(invokeResult, HttpStatus.BAD_REQUEST);
            }
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.OK);
    }

}
